<?php
class Cts_Config_Ini
{
    public function parseIniFile($filename,$section = null,$processSections = true)
    {
        // get contents of a ini file into a string
        if (empty($filename)) {
            /**
             * @see Zend_Config_Exception
             */
            require_once 'Zend/Config/Exception.php';
            throw new Zend_Config_Exception('Filename is not set');
        }
        $handle = fopen($filename, "r");
        $contents = fread($handle, filesize ($filename));
        fclose($handle);  
        
        //parse string to array
        $strPreProcessedContent = $this->clearComments($contents);
        $aPreProcessedArray = explode("[",$strPreProcessedContent);
        $aIniArray = array();
        $nCountPreProcessed = count($aPreProcessedArray);
        for( $nIndexI = 1 ; $nIndexI < $nCountPreProcessed ; $nIndexI++ )
        {
            $aSectionArray = $this->parseArray($aPreProcessedArray[$nIndexI]) ;
            $aIniArray = array_merge( $aIniArray , $aSectionArray );    
        }
        
        return $aIniArray ;  
    }
    
    private function clearComments($strContents)
    {
        $aProcessedArray = explode("\n",$strContents);
        foreach($aProcessedArray as $k => $v)
        {
            $strRow = trim($v) ;
            if( strcmp( $strRow[0] , ';' ) == 0 || empty($strRow) )
            {
                unset($aProcessedArray[$k]) ;
            }      
        }
        $strProcessedContent = implode("\n",$aProcessedArray);
        return $strProcessedContent ;
    }
    
    private function parseArray($aSection)
    {
        $aSection = explode("\n",$aSection);
        $nCountSection = count($aSection);
        $aParseArray = array();
        $aTempArray = array();
        for( $nIndexI == 0 ; $nIndexI < $nCountSection ; $nIndexI++ )
        {
            if( $nIndexI == 0 )
            {
                //explode section string by charset ']', the first item is section.
                $aTempSection = explode("]",$aSection[0]);
                $strSectionNode = $aTempSection[0];
            }
            else
            {
                $strRow = trim($aSection[$nIndexI]) ;
                if( !empty($strRow) )
                {
                    $aTempRow = $this->parseRow($aSection[$nIndexI]);
                    $aTempArray = array_merge( $aTempArray , $aTempRow );              
                }
            }
        }
        $aParseArray = array_merge( $aParseArray , array( $strSectionNode => $aTempArray ) );
        return $aParseArray ;
    }
    
    private function parseRow($strRow)
    {
        $strRow = trim($strRow);
        $aRow = explode("=",$strRow);
        $strValue = str_replace("\"",NULL,$aRow[1]);
        $aRowResult = array( trim($aRow[0]) => trim($strValue) );
        return $aRowResult ;
    }
}